package com.suvel.study.service.impl;

import com.suvel.study.dao.UserDao;
import com.suvel.study.pojo.User;
import com.suvel.study.service.CodeService;
import com.suvel.study.service.TokenService;
import com.suvel.study.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Reference(timeout = 2000)
    private CodeService codeService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private TokenService tokenService;

    @Override
    public User register(String email, String password, String code) {
        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(password) || StringUtils.isEmpty(code)){
            throw new RuntimeException("参数错误，注册失败！");
        }
        Integer validate = codeService.validate(email, code);
        if(!validate.equals(0)){
            throw new RuntimeException("验证码错误，注册失败！");
        }
        boolean registered = isRegistered(email);
        if(registered){
            throw new RuntimeException("用户已存在，注册失败！");
        }
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        User saveUser = new User();
        saveUser.setEmail(email);
        saveUser.setPassword(password);
        return userDao.save(saveUser);
    }

    public boolean isRegistered(String email) {
        boolean result = false;
        if(!StringUtils.isEmpty(email)){
           List<User> userList = userDao.findByEmail(email);
           if(!CollectionUtils.isEmpty(userList)){
               result = true;
           }
        }
        return result;

    }

    @Override
    public boolean login(String email, String password) {
        boolean result = false;
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        List<User> userList = userDao.findByEmailAndPassword(email,password);
        if(!CollectionUtils.isEmpty(userList)){
            result = true;
        }
        return result;
    }

    @Override
    public String info(String token) {
        String email = null;
        try {
            email = tokenService.findEmailByToken(token);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return email;
    }
}
